package com.xcc.gserver;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class StartListener implements ServletContextListener {
    private static final String GradleTmpDir = "GradleTmp";//临时目录名称
    private static final String PathDir = File.separator + "repository";//储存目录名称

    private static StartListener startListener;

    private File path, gradleTmpFile;
    private Runnable runnable;

    public static StartListener getInstance() {
        return startListener;
    }

    /**
     * @return 储存位置
     */
    public File getPath() {
        return path;
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        startListener = this;
        System.out.println("------------------MyGradleServer_Start------------------");

        ServletContext servletContext = sce.getServletContext();
        path = new File(servletContext.getRealPath(PathDir));
        gradleTmpFile = new File(servletContext.getRealPath(File.separator + GradleTmpDir));//临时储存目录
        if (!path.exists()) path.mkdir();
        if (!gradleTmpFile.exists()) gradleTmpFile.mkdir();

        runnable = () -> {
            //搬运文件
            File[] files = gradleTmpFile.listFiles();
            moveFile(files);
            deleteNullDir(files);
            //睡觉
            if (runnable == null) return;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
            if (runnable == null) return;
            runThread(runnable);
        };
        runThread(runnable);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("------------------MyGradleServer_Stop------------------");
        runnable = null;
    }

    private void runThread(Runnable runnable) {
        Thread thread = new Thread(runnable);
        //thread.setDaemon(true);
        thread.start();
    }

    private void moveFile(File[] files) {
        if (files == null) return;
        for (int i = 0; i < files.length; i++) {
            if (runnable == null) return;//直接结束
            File file = files[i];
            if (file.isDirectory()) {
                File[] listFiles = file.listFiles();
                moveFile(listFiles);
            } else moveFile(file);
        }
    }

    private void moveFile(File file) {
        if (runnable == null || file == null) return;//直接结束
        String fileAbsolutePath = file.getAbsolutePath();
        String[] split = fileAbsolutePath.split(GradleTmpDir);
        if (split.length != 2) return;
        String s = split[1];//相对目录
        //remove File.separator
        if (s.startsWith("/") || s.startsWith("\\")) {
            char[] chars = s.toCharArray();
            s = new String(chars, 1, chars.length - 1);
        }
        if (s.contains("/")) {
            split = s.split("/");//分割后的目录名称
        } else split = s.split("\\\\");//分割后的目录名称
        if (split.length < 2) return;

        StringBuilder builder = new StringBuilder();
        String s1 = split[0];//com.google.gson
        String[] split1 = s1.split("\\.");
        for (int i = 0; i < split1.length; i++) {
            builder.append(split1[i]).append(File.separator);
        }
        final int length = split.length;
        for (int i = 1; i < length; i++) {
            if (length == i + 2) continue;
            builder.append(split[i]);
            if (length == i + 1) continue;
            builder.append(File.separator);
        }
        File newFile = new File(path, builder.toString());
        File parentFile = newFile.getParentFile();
        if (!parentFile.exists()) parentFile.mkdirs();
        file.renameTo(newFile);
    }

    private void deleteNullDir(File[] files) {//删空目录
        if (files == null || files.length == 0) return;
        for (int i = 0; i < files.length; i++) {
            if (runnable == null) return;//直接结束
            File file = files[i];
            if (file.isDirectory()) {
                File[] listFiles = file.listFiles();
                if (listFiles == null || listFiles.length == 0) {//删除
                    file.delete();
                } else deleteNullDir(listFiles);
            }
        }
    }
}
